import { defineEventHandler, getRouterParams, getQuery } from 'h3'
import { verifyToken } from '../../utils/auth'
import prisma from '../../utils/prisma'

export default defineEventHandler(async (event) => {
  try {
    // Token验证
    const authHeader = getHeader(event, 'authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw createError({ statusCode: 401, message: '未提供认证令牌' })
    }
    
    const token = authHeader.slice(7)
    const decoded = verifyToken(token)
    if (!decoded) {
      throw createError({ statusCode: 401, message: '令牌无效或已过期' })
    }
    
    const { id } = getRouterParams(event)
    const query = getQuery(event)
    const { username } = query
    
    if (!username) {
      throw createError({ statusCode: 400, message: '需要提供用户名' })
    }
    
    // 验证学习记录是否存在且属于该用户
    const user = await prisma.user.findUnique({
      where: { username: username as string },
      include: { studies: { where: { id: parseInt(id) } } }
    })
    
    if (!user) {
      throw createError({ statusCode: 404, message: '用户不存在' })
    }
    
    if (user.studies.length === 0) {
      throw createError({ statusCode: 404, message: '学习记录不存在或无权访问' })
    }
    
    // 删除学习记录
    await prisma.study.delete({
      where: { id: parseInt(id) }
    })
    
    return {
      code: 200,
      message: '学习记录删除成功'
    }
    
  } catch (error: any) {
    console.error('删除学习记录失败:', error)
    throw createError({
      statusCode: error.statusCode || 500,
      message: error.message || '删除学习记录失败'
    })
  }
})